package TreeNode;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Admin
 * Date: 2022-06-06
 * Time: 21:38
 */
public class binarySearchTree {

    static class TreeNode {
        public int key;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    public boolean insert(int key) {
        TreeNode node = new TreeNode(key);
        if(root == null) {
            root = node;
            return true;
        }

        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null) {

            if(cur.key < key) {
                prev = cur;
                cur = cur.right;
            }else if(cur.key > key){
                prev = cur;
                cur = cur.left;
            }else {
                return false;
            }
        }

        if(prev.key > key ) {
            prev.left = node;
        }else {
            prev.right = node;
        }
        return true;
    }

    public void inorder(TreeNode root) {
        if(root == null) return;

        inorder(root.left);
        System.out.print(root.key + " ");
        inorder(root.right);
    }

    public TreeNode search(int key) {
        if(root == null)  return null;

        TreeNode cur = root;

        while(cur != null) {
            if(cur.key < key) {
                cur = cur.right;
            } else if(cur.key > key) {
                cur = cur.left;
            }  else {
                return cur;
            }
        }
        return null;
    }

    public boolean remove(int key) {
        if(root == null) return false;

        TreeNode cur = root;
        TreeNode prent = null;

        while(cur != null) {
            if(cur.key < key) {
                prent = cur;
                cur = cur.right;
            } else if(cur.key > key) {
                prent =cur;
                cur = cur.left;
            } else {
                removeNode(prent,cur);
                return true;
            }
        }

        return false;
    }

    public void removeNode(TreeNode prent,TreeNode cur) {
        if(cur.left == null) {
            if(prent == root) {
                root = prent.left;
            } else if(prent.left == null) {

            }
        }else if(cur.right == null){

        }else {

        }
    }
}
